// 引入XMLHttpRequest
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

// 封装ajax请求（get || post）
function sendData(options) {
    // 初始化配置信息
	options = options || {};
	options.method = (options.method || "GET").toUpperCase();
	options.dataType = options.dataType || "json";
	const params = options.data;

	// 创建XMLHttpRequest对象
	const xhr = new XMLHttpRequest();

    // get请求
	if (options.method === "GET") {
		xhr.open("GET", options.url + "?" + getParams(params), true);
		xhr.send();
    } else {
        // post请求
		xhr.open("POST", options.url, true);
		xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xhr.send(getParams(params));
	}

    // 设置状态监听
	xhr.onreadystatechange = function () {
		if (xhr.readyState === 4) {
			if (xhr.status >= 200 && xhr.status < 300) {
				options.success(xhr.responseText);
			} else {
				options.fail("错误状态码" + xhr.status);
			}
		}
	};
}

// 格式化参数：key1=value1&key2=value2&...
function getParams(data) {
	let arr = [];
	for (let key in data) {
		if (data.hasOwnProperty(key)) {
			arr.push(`${key}=${data[key]}`);
		}
	}
	return arr.join("&");
}

// 发送请求
sendData({
	url: "http://localhost:8080/list1",
	method: "POST",
	data: {
		limit: 10,
	},
	dataType: "json",
	success: (res) => {
		console.log(res);
	},
	fail: (errStatus) => {
		console.log(errStatus);
	},
});
